package com.gitee.clarence.business.user.controller;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gitee.clarence.business.user.model.User;
import com.gitee.clarence.business.user.ro.UserLoginRO;
import com.gitee.clarence.business.user.ro.UserRegisterRO;
import com.gitee.clarence.business.user.service.UserService;
import com.gitee.clarence.common.dataobject.vo.ResultVO;
import com.gitee.clarence.common.enums.ResultEnum;
import com.gitee.clarence.util.ROValidUtil;
import com.gitee.clarence.util.ResultVOUtil;

/**
 * @desc 用户信息
 * 
 * @author luocheng
 *
 */
@RestController
@SuppressWarnings("rawtypes")
@RequestMapping(value = "/api/v1/user", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public class UserController {

	@Autowired
	private UserService userService;

	/**
	 * 用户登录
	 *
	 * @param userLoginRO
	 * @return
	 */
	@PostMapping("/login")
	public ResultVO userLogin(@RequestBody UserLoginRO userLoginRO) {
		Map<String, Object> loginMap = userService.normalUserLogin(userLoginRO);
		if (loginMap.get("error") == null) {
			return ResultVOUtil.returnSuccess(loginMap);
		}
		return ResultVOUtil.returnFail((ResultEnum) loginMap.get("error"));
	}

	/**
	 * 用户注册
	 *
	 * @param userRegisterRO
	 * @return
	 */
	@PostMapping("/register")
	public ResultVO userRegister(@Valid @RequestBody UserRegisterRO userRegisterRO, BindingResult result) {
		ROValidUtil.valid(result);
		User user = userService.normalUserRegister(userRegisterRO);
		if (user != null) {
			return ResultVOUtil.returnSuccess();
		} else {
			return ResultVOUtil.returnFail();
		}
	}

	/**
	 * 获取所有用户
	 * 
	 * @return
	 */
	@GetMapping("")
	public ResultVO getUserList() {

		List<User> users = userService.findAll();

		if (users != null) {
			return ResultVOUtil.returnSuccess(users);
		} else {
			return ResultVOUtil.returnFail();
		}

	}

	/**
	 * 获取用户
	 * 
	 * @param id 用户id
	 * @return
	 */
	@GetMapping("/{id}")
	public ResultVO getUser(@PathVariable Integer id) {

		User user = userService.findById(id);
		if (user != null) {
			return ResultVOUtil.returnSuccess(user);
		} else {
			return ResultVOUtil.returnFail();
		}
	}

}